//
//  MyOrderDetailViewController.m
//  customer
//
//  Created by Holothurian on 2018/11/8.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "MyOrderDetailViewController.h"
#import "OneKeyRepairMainTableCell.h"
#import "SelectRepairDetailRegionTableCell.h"
#import "MyOrderStateTableViewCell.h"
#import "TicketCenterViewTableViewCell.h"
#import "SsehInvoiceTitleViewController.h"
#import "OrderScoreServiceViewController.h"


static NSString *OrderStateCellIdentifier = @"OrderStateCellIdentifier";//订单状态
static NSString *ContactInfoCellIdentifier = @"ContactInfoCellIdentifier";//联系人信息
static NSString *DefaultCellIdentifier = @"DefaultCellIdentifier";//默认title subTitle
static NSString *WorkerInfoCellIdentifier = @"WorkerInfoCellIdentifier";//维修师傅
static NSString *SelectRepairDetailCellID = @"SelectRepairDetailCellID";//
static NSString *RepairRegionCellIdentifier = @"RepairRegionCellIdentifier";
static NSString *UploadImageCellIdentifier = @"UploadImageCellIdentifier";
static NSString *QuestionCellIdentifier = @"QuestionCellIdentifier";
@interface MyOrderDetailViewController ()<UITableViewDelegate,UITableViewDataSource,OneKeyRepairUploadImageTableCellDelegate,UIAlertViewDelegate>

@property (nonatomic,strong)OrderDetailModel *orderModel;
/**
 图片数组
 */
@property (nonatomic,strong)NSMutableArray *imgUrlArray;

/**
 维修部位数组
 */
@property (nonatomic,strong)NSArray *repairArray;

@property (nonatomic,copy)NSMutableString *serviceTime;

@property (nonatomic,strong)UIView *bottomView;

/**
 删除订单
 */
@property (nonatomic,strong)UIButton *deleteButton;

/**
 联系客服
 */
@property (nonatomic,strong)UIButton *serviceMobileButton;

/**
 索取发票
 */
@property (nonatomic,strong)UIButton *chargeButton;

/**
 服务评价
 */
@property (nonatomic,strong)UIButton *serviceStarButton;

@property (nonatomic,strong)NSMutableArray *freeArray;

@property (nonatomic,strong)NSMutableArray *chargeArray;

@end

@implementation MyOrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createMainView];
}

- (void)backTapClick{
    self.isPop = YES;
    self.popArray = @[[NSString stringWithFormat:@"%ld",self.viewTag]];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter]postNotificationName:kPostNotificationForRepairOrder object:@{@"postIndex":[NSString stringWithFormat:@"%ld",self.viewTag]} userInfo:nil];
    });
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.isPop) {
        NSString *orderId = self.popArray.firstObject;
        if (!k_Is_Empty(orderId)) {
            self.orderId = orderId;
            [self loadDataList];
        }
    }
}

- (void)createMainView{
    self.title = @"订单详情";
    AutoWeakSelf
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(NAVIGATION_BAR_HEIGHT);
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_offset(F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(50));
    }];
    self.tableView.bounces = NO;
    [self.tableView registerClass:[MyOrderDetailOrderStateTableCell class] forCellReuseIdentifier:OrderStateCellIdentifier];
    [self.tableView registerClass:[MyOrderDetailAddressTableCell class] forCellReuseIdentifier:ContactInfoCellIdentifier];
    [self.tableView registerClass:[TicketDetailDefaultTableCell class] forCellReuseIdentifier:DefaultCellIdentifier];
    [self.tableView registerClass:[MyOrderDetailServicePersionTableCell class] forCellReuseIdentifier:WorkerInfoCellIdentifier];
    [self.tableView registerClass:[SelectedRepairRegionInfoTableCell class] forCellReuseIdentifier:SelectRepairDetailCellID];
    [self.tableView registerClass:[OneKeyRepairRegionTableCell class] forCellReuseIdentifier:RepairRegionCellIdentifier];
    [self.tableView registerClass:[OneKeyRepairUploadImageTableCell class] forCellReuseIdentifier:UploadImageCellIdentifier];
    [self.tableView registerClass:[OneKeyRepairQuestionDescriptionTableCell class] forCellReuseIdentifier:QuestionCellIdentifier];
    self.bottomView = [[UIView alloc]init];
    self.bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view).offset(-bottomPadding(0));
        make.height.mas_offset(50);
    }];

    CGFloat equalWidth = F_DEVICE_W / 5.0;
    CGFloat equalBargin = equalWidth / 6.0;
    NSArray *titleArray = @[@"删除订单",@"联系客服",@"索取发票",@"服务评价"];
    for (NSInteger i = 0; i < titleArray.count; i++) {
        UIButton *tempBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [tempBtn setTitle:titleArray[i] forState:UIControlStateNormal];
        [tempBtn setTitle:titleArray[i] forState:UIControlStateSelected];
        [tempBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [tempBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [tempBtn setBackgroundColor:[UIColor whiteColor]];
        [tempBtn addTarget:self action:@selector(bottomButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        tempBtn.layer.borderWidth = 1;
        tempBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        tempBtn.layer.cornerRadius = 3;
        tempBtn.layer.masksToBounds = YES;
        tempBtn.titleLabel.font = Font(12);
        tempBtn.hidden = YES;
        [self.bottomView addSubview:tempBtn];
        [tempBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf.bottomView).offset((2 *equalBargin + i * (equalWidth + equalBargin)));
            make.top.equalTo(weakSelf.bottomView).mas_offset(10);
            make.size.mas_equalTo(CGSizeMake(equalWidth, 30));
        }];
        switch (i) {
            case 0:{ self.deleteButton = tempBtn;}          break;
            case 1:{ self.serviceMobileButton = tempBtn;}   break;
            case 2:{ self.chargeButton = tempBtn;}          break;
            case 3:{ self.serviceStarButton = tempBtn;}     break;
            default: break;
        }
    }
}

- (void)bottomButtonAction:(UIButton *)sender{
    NSInteger index = sender.tag ;
    switch (index) {
        case 200:{//取消订单
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self showLoadingTitle:@"正在取消订单..."];
                [self cancelOrDeleteMaintailOrderActionURL:kCancelMaintailOrder OrderId:self.orderId];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认取消订单?" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];           
        }break;
        case 201:{//联系客服
            SHOW_ALERT(@"联系客服",kContactPhone?:@"", @"取消",@"确定", 100);
        }break;
        case 202:{//立即确认
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self showTipWithTitle:@"正在确认..."];
                [self cancelOrDeleteMaintailOrderActionURL:kAcceptMaintailOrder OrderId:self.orderId];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定已知维修报价并需要维修？" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
            
        }break;
        case 203:{//立即支付
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self payMaintailOrder];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定已知维修报价并需要维修" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
        }break;
        case 204:{//删除订单
            UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self showLoadingTitle:@"正在删除订单..."];
                [self cancelOrDeleteMaintailOrderActionURL:kDeleteMaintailOrder OrderId:self.orderId];
            }];
            UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确认删除订单?" preferredStyle:UIAlertControllerStyleAlert];
            [aleVC addAction:act1];
            [aleVC addAction:act2];
            [self presentViewController:aleVC animated:YES completion:nil];
            
        }break;
        case 205:{//索取发票
            SsehInvoiceTitleViewController *invoiceVC = [[SsehInvoiceTitleViewController alloc]init];
            invoiceVC.orderModel = self.orderModel;
            invoiceVC.comeIndex = 1;
            TAB_PUSH(self, invoiceVC, YES);
        }break;
        case 206:{//服务评价
            OrderScoreServiceViewController *scoreVC = [[OrderScoreServiceViewController alloc]init];
            scoreVC.order_id = self.orderModel.order_id;
            TAB_PUSH(self, scoreVC, YES);
        }break;
        default:
            break;
    }
}
- (void)payMaintailOrder{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:K_UserDefault_Read(CustomerUserID)?:@"" forKey:@"member_id"];
    [dict setObject:K_UserDefault_Read(CustomerUserToken)?:@"" forKey:@"member_token"];
    [dict setObject:self.orderModel.order_id?:@"" forKey:@"order_id"];
    [dict setObject:@"wx" forKey:@"pay_way"];
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kPayMaintailOrder parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                PayOrderModel *payModel = [PayOrderModel yy_modelWithDictionary:responseObject[@"data"]];
                __block typeof(weakSelf) strongSelf = weakSelf;
                [PayStyleUtil doWxpay:payModel payDone:^(NSString * _Nonnull errorMsg) {
                    if (!errorMsg) {
                        [strongSelf showTipWithTitle:@"支付成功"];
                        [strongSelf useMyCoupon];
                    }else{
                        [strongSelf showErrorTipWithTitle:errorMsg];
                    }
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [strongSelf loadDataList];
                    });
                }];
            }
        }else{
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [weakSelf showErrorTipWithTitle:error.localizedDescription];
    }];
}

- (void)useMyCoupon {
    
    if (self.orderModel.coupon != nil) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:0];
        [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserID)] forKey:@"member_id"];
        [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)] forKey:@"member_token"];
        [dict setObject:self.orderModel.order_id?:@"" forKey:@"order_id"];
        [dict setObject:@"1" forKey:@"order_type"];
        [dict setObject:@"2" forKey:@"flag"];
        [dict setObject:self.orderModel.coupon[@"id"]?:@"" forKey:@"id"];
        
        [[QYNetManager sharedManager]POST:kUseCoupon parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
           
        } Failure:^(NSError *error) {
            
        }];
    }
}



/**
 取消订单、删除订单
 */
- (void)cancelOrDeleteMaintailOrderActionURL:(NSString *)actionUrl OrderId:(NSString *)order_id{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:K_UserDefault_Read(CustomerUserID)?:@"" forKey:@"member_id"];
    [dict setObject:K_UserDefault_Read(CustomerUserToken)?:@"" forKey:@"member_token"];
    [dict setObject:order_id?:@"" forKey:@"order_id"];
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:actionUrl parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        NSString * statusStr = [NSString stringWithFormat:@"%@",responseObject[@"status"]];
        if ([statusStr isEqualToString:@"ok"]) {
            if ([responseObject[@"data"] integerValue]) {
                
                if ([actionUrl isEqualToString:kAcceptMaintailOrder]) {
                    [weakSelf loadDataList];
                    [weakSelf payMaintailOrder];
                }else{
                    [weakSelf showTipWithTitle:@"操作成功"];
                    [weakSelf loadDataList];
                }
            }else{
                [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
            }
        }else{
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:error.localizedDescription];
    }];
}

- (void)initButtonState{
    self.deleteButton.hidden = NO;
    self.serviceMobileButton.hidden = NO;
    self.chargeButton.hidden = NO;
    self.serviceStarButton.hidden = NO;
    self.deleteButton.tag = 0;
    self.serviceMobileButton.tag = 0;
    self.chargeButton.tag = 0;
    self.serviceStarButton.tag = 0;
}

- (void)loadDataList{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:K_UserDefault_Read(CustomerUserID)?:@"" forKey:@"member_id"];
    [dict setObject:K_UserDefault_Read(CustomerUserToken)?:@"" forKey:@"member_token"];
    [dict setObject:self.orderId forKey:@"order_id"];
    [self showLoading];
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kGetMaintailOrderDetail parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf endReresh];
        [weakSelf hideLoading];
        weakSelf.tableView.showEmpty = NO;
        id resultData = responseObject[@"data"];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else if (![resultData isKindOfClass:[NSNull class]] && [resultData isKindOfClass:[NSDictionary class]] && [[resultData allKeys] count]){
            OrderDetailModel *detailModel = [OrderDetailModel yy_modelWithDictionary:resultData];            
            weakSelf.orderModel = detailModel;
           
            weakSelf.repairArray = [detailModel.parts_names componentsSeparatedByString:@","];
            weakSelf.imgUrlArray = [NSMutableArray arrayWithArray:[detailModel.maintail_imgs componentsSeparatedByString:@","]];
            NSArray *serviceStartArr = [detailModel.service_start_time componentsSeparatedByString:@" "];
            NSArray *serviceEndArr = [detailModel.service_end_time componentsSeparatedByString:@" "];
            weakSelf.serviceTime = [NSMutableString stringWithFormat:@"%@\n %@-%@",serviceStartArr.firstObject,serviceStartArr.lastObject,serviceEndArr.lastObject];
            
            NSArray *materialBeanArr = weakSelf.orderModel.maintailOrderMaterialBeans;
            weakSelf.freeArray = [NSMutableArray array];
            weakSelf.chargeArray = [NSMutableArray array];
            if ([materialBeanArr count]) {
                for (MaintailOrderMaterialBean *beanModel in materialBeanArr) {
                    if ([beanModel.material_price isEqualToString:@"0"]) {
                        [weakSelf.freeArray addObject:beanModel];
                    }else{
                        [weakSelf.chargeArray addObject:beanModel];
                    }
                }
            }
            [weakSelf.tableView reloadData];
            [weakSelf currentButtonState:detailModel];
            
        }else{
            self.tableView.showEmpty = YES;
        }
    } Failure:^(NSError *error) {
        [weakSelf endReresh];
        [weakSelf hideLoading];
        [weakSelf.tableView reloadData];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

- (void)currentButtonState:(OrderDetailModel *)model{
    [self initButtonState];
    AutoWeakSelf
    // 0:已取消 1:待指派  2:待上门  3:等待确认服务  4:待付款  5:已付款
    if ([model.order_state isEqualToString:@"0"]) {
        [self.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.view);
            make.bottom.equalTo(weakSelf.view).offset(0);
            make.height.mas_offset(0);
        }];
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.view).offset(NAVIGATION_BAR_HEIGHT);
            make.left.right.equalTo(weakSelf.view);
            make.height.mas_offset(F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(0));
        }];
    }
    else if ([model.order_state isEqualToString:@"1"]||[model.order_state isEqualToString:@"2"]){
        self.deleteButton.hidden = YES;
        self.serviceMobileButton.hidden = YES;
        self.chargeButton.tag = 200;
        self.serviceStarButton.tag = 201;
        [self changeCurrentButton:self.chargeButton Title:@"取消订单" TitleColor:[HSPublic colorWithHexString:@"#666666"] BackgroundColor:[UIColor whiteColor]];
        [self changeCurrentButton:self.serviceStarButton Title:@"联系客服" TitleColor:[UIColor whiteColor] BackgroundColor:[HSPublic colorWithHexString:@"#1F89FF"]];
    }
    else if ([model.order_state isEqualToString:@"3"]){
        self.deleteButton.hidden = YES;
        self.serviceMobileButton.tag = 200;
        self.chargeButton.tag = 201;
        self.serviceStarButton.tag = 202;
        [self changeCurrentButton:self.serviceMobileButton Title:@"取消订单" TitleColor:[HSPublic colorWithHexString:@"#666666"] BackgroundColor:[UIColor whiteColor]];
        [self changeCurrentButton:self.chargeButton Title:@"联系客服" TitleColor:[UIColor whiteColor] BackgroundColor:[HSPublic colorWithHexString:@"#1F89FF"]];
        [self changeCurrentButton:self.serviceStarButton Title:@"立即确认" TitleColor:[UIColor whiteColor] BackgroundColor:[HSPublic colorWithHexString:@"#1F89FF"]];
    }
    else if ([model.order_state isEqualToString:@"4"]){
        self.deleteButton.hidden = YES;
        self.serviceMobileButton.tag = 200;
        self.chargeButton.tag = 201;
        self.serviceStarButton.tag = 203;
        [self changeCurrentButton:self.serviceMobileButton Title:@"取消订单" TitleColor:[HSPublic colorWithHexString:@"#666666"] BackgroundColor:[UIColor whiteColor]];
        [self changeCurrentButton:self.chargeButton Title:@"联系客服" TitleColor:[UIColor whiteColor] BackgroundColor:[HSPublic colorWithHexString:@"#1F89FF"]];
        [self changeCurrentButton:self.serviceStarButton Title:@"立即支付" TitleColor:[UIColor whiteColor] BackgroundColor:[HSPublic colorWithHexString:@"#1F89FF"]];
    }
    else if ([model.order_state isEqualToString:@"5"]){
        self.deleteButton.tag = 204;
        self.serviceMobileButton.tag = 201;
        [self changeCurrentButton:self.deleteButton Title:@"删除订单" TitleColor:[HSPublic colorWithHexString:@"D51A28"] BackgroundColor:[UIColor whiteColor]];
        [self changeCurrentButton:self.serviceMobileButton Title:@"联系客服" TitleColor:[UIColor whiteColor] BackgroundColor:[HSPublic colorWithHexString:@"#1F89FF"]];
        //评价状态 1:未评价 2:已评价
        if ([model.assessment_state isEqualToString:@"1"]) {
            self.serviceStarButton.tag = 206;
            self.serviceStarButton.enabled = YES;
            [self changeCurrentButton:self.serviceStarButton Title:@"服务评价" TitleColor:[UIColor whiteColor] BackgroundColor:[HSPublic colorWithHexString:@"#1F89FF"]];
        }else{
            self.serviceStarButton.enabled = NO;
            [self changeCurrentButton:self.serviceStarButton Title:@"已评价" TitleColor:[UIColor whiteColor] BackgroundColor:[HSPublic colorWithHexString:@"#B5B4B4"]];
        }
        //invoice_state 1:未申请 2:已申请 3:已寄出 4:拒绝
        if (![self.orderModel.invoice_state isEqualToString:@"1"]) {
            self.chargeButton.enabled = NO;
            [self changeCurrentButton:self.chargeButton Title:@"已索取发票" TitleColor:[UIColor whiteColor] BackgroundColor:[HSPublic colorWithHexString:@"#B5B4B4"]];
        }else{
            self.chargeButton.tag = 205;
            self.chargeButton.enabled = YES;
            [self changeCurrentButton:self.chargeButton Title:@"索取发票" TitleColor:[UIColor whiteColor] BackgroundColor:[HSPublic colorWithHexString:@"#1F89FF"]];
        }
    }
}

- (void)changeCurrentButton:(UIButton *)currentButton Title:(NSString *)title TitleColor:(UIColor *)titleColor BackgroundColor:(UIColor *)backgroundColor{
    [currentButton setTitle:title?:@"" forState:UIControlStateNormal];
    [currentButton setTitle:title?:@"" forState:UIControlStateSelected];
    [currentButton setTitleColor:titleColor?:[UIColor blackColor] forState:UIControlStateNormal];
    [currentButton setTitleColor:titleColor?:[UIColor blackColor] forState:UIControlStateSelected];
    [currentButton setBackgroundColor:backgroundColor?:[UIColor whiteColor]];
    currentButton.layer.borderColor = titleColor.CGColor;
}





//0:已取消 1:待指派  2:待上门  3:等待确认服务  4:待付款  5:已付款
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([self.orderModel.order_state isEqualToString:@"3"]||[self.orderModel.order_state isEqualToString:@"4"]||[self.orderModel.order_state isEqualToString:@"5"]) {
        return 8;
    }
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 2){
        return 2;
    }else if (section == 3&&[self.repairArray count] == 3){//1或者2
        NSString *partsName = self.repairArray[2];
        if ([HSPublic hsBoundingRectWithWidthString:partsName SizeHeight:50 Font:Font(20)]>(F_DEVICE_W/2.0-60)) {
            return 2;
        }else{
            return 1;
        }
    }else if (section == 4){
        return 2;
    }else if (section == 5){//待定
        return self.chargeArray.count;
    }else if (section == 6){//待定
        return self.freeArray.count;
    }else if (section == 7){
        if (self.orderModel.coupon != nil) {
            return 2;
        }
        return 1;
    }else{
        return 1;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        MyOrderDetailOrderStateTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:OrderStateCellIdentifier];
        [cell cellForLayout:self.orderModel];
        return cell;
    }
    else if (indexPath.section == 1){
        MyOrderDetailAddressTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:ContactInfoCellIdentifier];
        [cell cellForLayout:self.orderModel];
        return cell;
    }
    else if (indexPath.section == 2){
        if (indexPath.row == 0) {
            TicketDetailDefaultTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DefaultCellIdentifier];
            [cell cellRemarkForOrderDetailServiceTimeUse];
            cell.nameLabel.text = @"服务时间";
            cell.subTitleLabel.text = self.serviceTime?:@"";
            return cell;
        }else if (indexPath.row == 1){
            //待指派师傅
            if (([self.orderModel.order_state isEqualToString:@"1"]&&[self.orderModel.accept_state isEqualToString:@"2"]) || k_Is_Empty(self.orderModel.workerBean.member_id)) {
                TicketDetailDefaultTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DefaultCellIdentifier];
                [cell cellRemarkForOrderDetailServiceTimeUse];
                cell.nameLabel.text = @"上门师傅";
                cell.subTitleLabel.text = @"待指派";
                return cell;
            }else{
                MyOrderDetailServicePersionTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:WorkerInfoCellIdentifier];
                [cell cellForLayout:self.orderModel];
                [cell.contactRepairsButton addTarget:self action:@selector(contactRepairButtonEvent) forControlEvents:UIControlEventTouchUpInside];
                return cell;
            }
        }
    }else if (indexPath.section == 3){
        if (indexPath.row == 0) {
            OneKeyRepairRegionTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:RepairRegionCellIdentifier];
            [cell cellForOrderDetailLayout:self.repairArray];
            return cell;
        }else{
            SelectedRepairRegionInfoTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:SelectRepairDetailCellID];
            NSString *itemName = self.repairArray[2];
            cell.nameLabel.text = itemName;
            return cell;
        }
    }else if (indexPath.section == 4){
        if (indexPath.row == 0) {
            OneKeyRepairUploadImageTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:UploadImageCellIdentifier];
            cell.orderDetailFlag = YES;
            cell.delegate = self;
            cell.dataSource = self.imgUrlArray;
            return cell;
        }else{
            OneKeyRepairQuestionDescriptionTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:QuestionCellIdentifier];
            cell.textView.text = self.orderModel.maintail_remark?:@"";
            [cell.textView setEditable:NO];
            return cell;
        }
    }
    else if (indexPath.section == 5){
        TicketDetailDefaultTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DefaultCellIdentifier];
        [cell cellReLayoutForOrderDetialChargeCell];
        MaintailOrderMaterialBean *beanModel = self.chargeArray[indexPath.row];
        cell.nameLabel.text = beanModel.material_name?:@"";
        cell.subTitleLabel.text = [NSString stringWithFormat:@"¥%@",beanModel.material_price?:@""];
        return cell;
    }
    else if (indexPath.section == 6){
        TicketDetailDefaultTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DefaultCellIdentifier];
        [cell cellReLayoutForOrderDetialChargeCell];
        MaintailOrderMaterialBean *beanModel = self.freeArray[indexPath.row];
        cell.nameLabel.text = beanModel.material_name?:@"";
        cell.subTitleLabel.text = [NSString stringWithFormat:@"¥%@",beanModel.material_price?:@""];
        return cell;
        
    }else if (indexPath.section == 7){
        TicketDetailDefaultTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DefaultCellIdentifier];
        [cell cellReLayoutForOrderDetialChargeCell];
        if (indexPath.row == 0 && (self.orderModel.coupon != nil)) {
            cell.nameLabel.text = @"优惠立减";
            float couponPrice = [self.orderModel.coupon[@"money"] floatValue];
            cell.subTitleLabel.text = [NSString stringWithFormat:@"¥%.2f", couponPrice];
        } else {
            cell.nameLabel.text = @"应付金额";
            float couponPrice = 0;
            if (self.orderModel.coupon != nil) {
                couponPrice = [self.orderModel.coupon[@"money"] floatValue];
            }
            float finalPrice = [self.orderModel.order_price floatValue] - couponPrice;
            if (finalPrice < 0) {
                finalPrice = 0;
            }
            cell.subTitleLabel.text = [NSString stringWithFormat:@"¥%.2f", finalPrice];
        }
        cell.subTitleLabel.textColor = [HSPublic colorWithHexString:@"#E51C23"];
        cell.contentView.backgroundColor = [UIColor whiteColor];
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 ||indexPath.section == 1) {
        return 100;
    }else if (indexPath.section == 2){
        if (indexPath.row == 0) {
            return 50.f;
        }else if (indexPath.row == 1){
            if (([self.orderModel.order_state isEqualToString:@"1"]&&[self.orderModel.accept_state isEqualToString:@"2"]) || k_Is_Empty(self.orderModel.worker_id)) {
                return 50.f;
            }
            return 60;
        }
    }else if (indexPath.section == 3){
        return 70;
    }else if (indexPath.section == 4){
        if (indexPath.row == 0) {
            return 100.f;
        }else{
            return 150.f;
        }
    }
    return 50.f;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 5.0;
    }else if(section == 2||section == 7){
        return 10.f;
    }else if (section == 3){
        return 50.f;
    }else if (section == 4){
        return 40.f;
    }else if (section == 5){
        if ([self.chargeArray count]==0) {
            return 0.001f;
        }
        return 40.f;
    }else if (section == 6){
        if ([self.freeArray count]==0) {
            return 0.001f;
        }
        return 40.f;
    }
    return 0.001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 4||section == 7) {
        return 30.f;
    }
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 10)];
    backView.backgroundColor = [UIColor appColor];
    if (section == 0) {
        return nil;
    }
    else if (section == 1) {
        backView.frame = CGRectMake(0, 0, F_DEVICE_W, 5);
    }else if (section == 3){
        backView.frame = CGRectMake(0, 0, F_DEVICE_W, 50);
        UIView *whiteView = [[UIView alloc]initWithFrame:CGRectMake(0, 10, F_DEVICE_W, 40)];
        whiteView.backgroundColor = [UIColor whiteColor];
        [backView addSubview:whiteView];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, F_DEVICE_W-20, 40)];
        titleLabel.text = @"维修需求";
        titleLabel.font = Font(16);
        titleLabel.textColor = [HSPublic colorWithHexString:@"#808080"];
        [whiteView addSubview:titleLabel];
    }else if (section == 4){
        backView.frame = CGRectMake(0, 0, F_DEVICE_W, 40);
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, F_DEVICE_W-20, 40)];
        titleLabel.text = @"维修拍照";
        titleLabel.font = Font(15);
        titleLabel.textColor = [HSPublic colorWithHexString:@"#808080"];
        [backView addSubview:titleLabel];
    }else if (section == 5 || section == 6){
        backView.frame = CGRectMake(0, 0, F_DEVICE_W, 40);
        backView.backgroundColor = [UIColor whiteColor];
        switch (section) {
            case 5:{
                if ([self.chargeArray count] == 0) {
                    return nil;
                }
            }break;
            case 6:{
                if ([self.freeArray count] == 0) {
                    return nil;
                }
            }break;
            default:
                break;
        }
        UIImageView *imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"orderDetialCharge"]];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imgView.frame = CGRectMake(15, 13, 15, 15);
        [backView addSubview:imgView];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(40, 0, F_DEVICE_W-60, 40)];
        titleLabel.text = @"维修清单-收费项";
        titleLabel.font = Font(14);
        titleLabel.textColor = [HSPublic colorWithHexString:@"333333"];
        [backView addSubview:titleLabel];
        if (section == 6) {
            titleLabel.text = @"维修清单-免费项";
        }
    }
    return backView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 4 || section == 7) {
        UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 30)];
        backView.backgroundColor = [UIColor appColor];
        return backView;
    }
    return nil;
}

#pragma mark - MyOrderDetailServicePersionTableCell
- (void)contactRepairButtonEvent{
    if (k_Is_Empty(self.orderModel.workerBean.member_account)) {
        return;
    }
    SHOW_ALERT(@"联系师傅",self.orderModel.workerBean.member_account?:@"" , @"取消",@"确定", 99);
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 99) {//联系师傅
        if (buttonIndex == 1) {
            NSString *ph1 = [NSString stringWithFormat:@"telprompt:%@",self.orderModel.workerBean.member_account];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ph1]];
        }
    }else if (alertView.tag == 100){//联系客服
        if (buttonIndex == 1) {
            NSString *ph1 = [NSString stringWithFormat:@"telprompt:%@",kContactPhone];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ph1]];
        }
    }
}


#pragma mark - OneKeyRepairUploadImageTableCellDelegate
- (void)uploadImageTableCellTapHaveALook:(NSIndexPath *)indexPath{
    HSImageScrollViewController *scrollVC = [[HSImageScrollViewController alloc]init];
    scrollVC.imgUrlArr = self.imgUrlArray;
    scrollVC.index = indexPath.row;
    [self.navigationController presentViewController:scrollVC animated:YES completion:nil];
}

- (void)uploadImageTableCellAddImage:(NSIndexPath *)indexPath{
    return;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
